/*
 * @Author: Zhang Wei
 * @Date: 2022-04-17 21:46:57
 * @LastEditors: Zhang Wei
 * @LastEditTime: 2022-04-18 00:23:08
 * @FilePath: \02_tank\src\model\TankModel.ts
 * @Word: There is nothing either good or bad, but thinking makes it so.
 * @Description: 坦克模型
 */

import _ from 'lodash';
import SteelCanvas from '../canvas/SteelCanvas';
import WallCanvas from '../canvas/WallCanvas';
import WaterCanvas from '../canvas/WaterCanvas';
import config from '../config';

import { image } from '../service/image';
import { directionEnum } from './../enum/directionEnum';

import ModelAbstract from './ModelAbstract';

export default class Model extends ModelAbstract implements IModel {
  name: string = 'tank';

  render(): void {
    this.move();
    // if (Math.floor(Math.random() * 5) == 1) {
    if (_.random(20) == 1) {
      this.direction = directionEnum.bottom;
    }
  }

  // 移动
  protected move(): void {
    let oldPosition = {
      x: this.x,
      y: this.y,
    };

    let newPosition = {
      x: this.x,
      y: this.y,
    };

    while (true) {
      switch (this.direction) {
        case directionEnum.top:
          newPosition.y = oldPosition.y - 2;
          break;

        case directionEnum.right:
          newPosition.x = oldPosition.x + 2;
          break;

        case directionEnum.bottom:
          newPosition.y = oldPosition.y + 2;
          break;

        case directionEnum.left:
          newPosition.x = oldPosition.x - 2;
          break;
      }

      if (this.isTouch(newPosition.x, newPosition.y) === true) {
        // 如果触碰边界，则随机改变方向
        this.randomDirection();
      } else {
        this.x = newPosition.x;
        this.y = newPosition.y;
        break;
      }
    }

    super.draw();
  }

  //是否触碰到边界
  protected isTouch(itemX: number, itemY: number): boolean {
    // 边界检测
    if (
      itemX <= 0 ||
      itemY <= 0 ||
      itemX + this.width >= config.canvas.width ||
      itemY + this.height >= config.canvas.height
    ) {
      return true;
    }

    // 元素检测
    const models = [...SteelCanvas.models, ...WallCanvas.models, ...WaterCanvas.models];

    return models.some((model) => {
      const status =
        itemX + this.width <= model.x ||
        itemX >= model.x + model.width ||
        itemY + this.height <= model.y ||
        itemY >= model.y + model.height;

      return !status;
    });
  }

  // 返回坦克图片
  getImg() {
    let direction = this.name + _.upperFirst(this.direction);
    return image.get(direction as keyof typeof config.images)!;
  }
}
